package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"plastic-company/internal/model"
)

// GetApplications 获取所有应用领域
func GetApplications(c *gin.Context) {
	var categories []struct {
		Category string `json:"category"`
	}

	db.Table("applications").Select("DISTINCT category").Find(&categories)

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data:    categories,
	})
}

// GetApplicationByCategory 获取特定应用领域的产品
func GetApplicationByCategory(c *gin.Context) {
	category := c.Param("category")

	var applications []model.Application
	result := db.Where("category = ?", category).Find(&applications)

	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "获取应用领域产品失败",
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data:    applications,
	})
}

// CreateApplication 创建应用领域产品
func CreateApplication(c *gin.Context) {
	var application model.Application

	if err := c.ShouldBindJSON(&application); err != nil {
		c.JSON(http.StatusBadRequest, model.APIResponse{
			Success: false,
			Message: "请求参数错误",
		})
		return
	}

	result := db.Create(&application)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "创建应用领域产品失败",
		})
		return
	}

	c.JSON(http.StatusCreated, model.APIResponse{
		Success: true,
		Message: "创建应用领域产品成功",
		Data:    application,
	})
}

// UpdateApplication 更新应用领域产品
func UpdateApplication(c *gin.Context) {
	id := c.Param("id")

	var application model.Application
	if err := c.ShouldBindJSON(&application); err != nil {
		c.JSON(http.StatusBadRequest, model.APIResponse{
			Success: false,
			Message: "请求参数错误",
		})
		return
	}

	result := db.Model(&application).Where("id = ?", id).Updates(&application)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "更新应用领域产品失败",
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "更新应用领域产品成功",
		Data:    application,
	})
}

// DeleteApplication 删除应用领域产品
func DeleteApplication(c *gin.Context) {
	id := c.Param("id")

	result := db.Delete(&model.Application{}, id)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "删除应用领域产品失败",
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "删除应用领域产品成功",
	})
}